from django import forms
from django.core.exceptions import ValidationError
from django.db.models import Q, QuerySet

from .models import SysUser

class LoginForm(forms.Form):
    name = forms.CharField(error_messages={
        'required': '账号不能为空'
    })

    pwd = forms.CharField(error_messages={
        'required': '口令不能为空'
    })

    def clean_name(self):
        # 验证系统是否存在此用户
        # name用户名或手机号
        name = self.cleaned_data.get('name')
        q:QuerySet = SysUser.objects.filter(Q(username=name)|Q(tel=name))
        if not q.exists():
            raise ValidationError(f'{name}, 查无此用户')

        self.instance_ = q.first()
